package com.rtsapp.server.domain;

import com.rtsapp.server.logger.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by admin on 15-11-24.
 */
public  class DBUtils {
    private static Logger LOGGER =com.rtsapp.server.logger.LoggerFactory.getLogger( DBUtils.class );

    private String host;
    private int port;
    private String database;
    private String characterEncoding;

    private String user;
    private String password;

    private DBUtils(){
    }

    static {
        try {
            Class.forName( "com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            LOGGER.error( "加载jdbc驱动 com.mysql.jdbc.Driver 出错", e );
        }
    }

    public static DBUtils newDBUtils( String host, int port, String username, String password, String database ){
        DBUtils utils = new DBUtils();

        utils.host = host;
        utils.port = port;
        utils.user = username;
        utils.password = password;
        utils.database = database;
        utils.characterEncoding = "UTF-8";

        return utils;
    }


    public Connection openConnection( ) throws  SQLException{
        return DriverManager.getConnection( getJDBCURL(), user,  password );
    }

    public ResultSet query( Connection con, String sql  ) throws  SQLException{
        return con.prepareStatement( sql ).executeQuery();
    }

    public void closeConnection( Connection con ) {
        try {
            if( con == null || con.isClosed() ){
                return;
            }
            con.close();
        } catch (SQLException e) {
           LOGGER.error( "closeConnection error" , e );
        }

    }



    public String getJDBCURL(){
        String url = "jdbc:mysql://" + this.getHost() + ":" + this.getPort() + "/" + this.getDatabase() + "?characterEncoding=" + this.getCharacterEncoding();
        return url;
    }


    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public String getDatabase() {
        return database;
    }

    public String getCharacterEncoding() {
        return characterEncoding;
    }

    public String getUser() {
        return user;
    }

    public String getPassword() {
        return password;
    }
}
